service.factory('appFactory',['$q','$timeout',function($q,$timeout){
    var storage = window.localStorage;
    var Courier = AV.Object.extend('Courier');
    var Config = AV.Object.extend('Config');
    var _data = {};
    var _loaded = false;

    var _service =
    {
        ready:function(){

            var q = $q.defer();
            var queryConfig = new AV.Query(Config);
            var key=['area','shopArea'];
            queryConfig.containedIn('key',key);
            queryConfig.ascending('key');
            queryConfig.find().then(function(data){
                storage.setItem('globalArea',JSON.stringify(data[0].get("info")));
                storage.setItem('shopArea',JSON.stringify(data[1].get("info")));
                _data.area = JSON.parse(storage.getItem("globalArea"));
                _data.shopArea = JSON.parse(storage.getItem("shopArea"));
                //console.log(JSON.parse(storage.getItem('globalArea')));
                q.resolve({});
            }).catch(function(err){
                storage.setItem('globalArea',false);
                q.reject({err:''});
            });

            return q.promise;

        },
        /**
         * 重新加载配置信息
         */
        reload:function(){
            //获取地址分区信息的匿名函数
            setTimeout(function(){
                var queryConfig = new AV.Query(Config);
                var key=['area','shopArea'];
                queryConfig.containedIn('key',key);
                queryConfig.ascending('key');
                queryConfig.find().then(function(data){
                    storage.setItem('globalArea',JSON.stringify(data[0].get("info")));
                    storage.setItem('shopArea',JSON.stringify(data[1].get("info")));
                    _data.area = JSON.parse(storage.getItem("globalArea"));
                    _data.shopArea = JSON.parse(storage.getItem("shopArea"));
                    //console.log(JSON.parse(storage.getItem('globalArea')));
                }).catch(function(err){
                    storage.setItem('globalArea',false);
                });
            },100);
            //加载用户信息
            _data.userInfo = {uid:JSON.parse(storage.getItem("uid")),user:JSON.parse(storage.getItem("user"))};
            //加载地址分区信息
            _data.isLogin = !(storage.getItem("uid")==undefined||storage.getItem("uid")==null||storage.getItem("uid")=="");
            _loaded = true;
        },
        /**
         * 获取用户信息
         * @returns {{uid, user}} uid type int,user object
         */
        getUserInfo:function(){
            return _data.userInfo;
        },
        /**
         *登陆
         * @param username
         * @param password
         * @returns {*} promise
         */
        doLogin:function(username,password) {
            var q = $q.defer();
            async.auto({
                query1:function(callback,results){
                    queryConfig=new AV.Query(Config);
                    queryConfig.equalTo("key","area");
                    queryConfig.first().then(function(res){
                        callback(null,res.get('info'));
                    }).catch(function(err){
                        callback(err);
                    })
                },
                query2:['query1',function(callback,results){
                    var areaObj=results;
                    //console.log(areaObj.query1[43].areaName);
                    query = new AV.Query(Courier);
                    query.equalTo("jobnumber",username);
                    query.equalTo("pwd",md5(password));
                    query.first().then(function(res){
                        if(res){
                            var areaNameTemp='';
                            var whNameTemp='';
                            for(var i=0;i<eval(res.get("area")).length;i++){
                                areaNameTemp+= areaObj.query1[ eval(res.get("area"))[i]].areaName+',';
                                whNameTemp+= areaObj.query1[ eval(res.get("area"))[i]].whName+',';
                            }
                            var user={
                                uid:res.id,
                                name:res.get("name"),
                                jobnumber:res.get("jobnumber"),
                                area:JSON.parse(res.get("area")),
                                phone:res.get("phone"),
                                areaName:areaNameTemp,
                                areaCN:whNameTemp
                            }
                            //console.log(user);
                            var userJson=JSON.stringify(user);
                            storage.setItem("uid",res.id);
                            storage.setItem("user",userJson);
                            _data.isLogin = true;
                            _data.userInfo = {uid:String(JSON.parse(storage.getItem("uid"))),user:JSON.parse(storage.getItem("user"))};
                            _service.ready().then(function(){
                                callback(null,{code:0,msg:'success'});
                            }).catch(function(){
                                callback(null,{code:2,msg:'fail'})
                            });

                        }else{
                            callback(null,{code:1,msg:'fail'})
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                }]
            },function(err,results){
                if(err){
                    q.reject(err);
                }else{
                    q.resolve(results);
                }
            })
            return q.promise;
        },
        /**
         * 是否登录
         * @returns {boolean}
         */
        isLogin:function(){
            return _data.isLogin;
        },
        /**
         * 获取地址列表
         * @return object{44:aa,45:ff}
         */
        globalArea:function (){
            return _data.area;
        },
        /**
         * 果饮店地址
         * @returns {*}
         */
        shopArea:function (){
            return _data.shopArea;
        },
        /**
         * 登出
         */
        loginOut:function(){
            storage.removeItem("user");
            storage.removeItem("globalArea");
            storage.removeItem("shopArea");
            storage.removeItem("uid");
            _data.isLogin=false;
        }
    };

    if(!_loaded){
        console.log('app service loaded');
        _service.reload();
    }
    return _service;
}]);
